package com.ruis.kotboot.common.util

import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component

/**
 *
 * @author NorthLan
 * @date 2018/2/1
 * @url https://noahlan.com
 */
@Component
class SpringContextHolder : ApplicationContextAware {
    companion object {
        private val logger = LoggerFactory.getLogger(SpringContextHolder::class.java)
        private lateinit var applicationContext: ApplicationContext

        @Suppress("UNCHECKED_CAST")
        fun <T> getBean(beanName: String): T {
            return applicationContext.getBean(beanName) as T
        }

        fun <T : Any> getBean(requiredType: Class<T>): T {
            return applicationContext.getBean(requiredType)
        }
    }

    init {
        logger.info("${this::class.java.simpleName} initializing...")
    }

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        SpringContextHolder.applicationContext = applicationContext
    }
}